﻿using System.Linq;
using Portal.Model;
using AutoMapper;
using System.Data;
using RepositoryFramework;

namespace Portal.Repository
{
	/// <summary>
	/// Class <see cref="UserRepository"/> define repository of user
	/// </summary>
	public class UserRepository : GenericRepository<PortalEntities, User>, IUserRepository
	{
		#region .ctor

		/// <summary>
		/// Class <see cref="UserRepository"/> constructor
		/// </summary>
		/// <param name="entities"></param>
		public UserRepository(PortalEntities entities)
			: base(entities)
		{
		}

		#endregion .ctor

		#region Methods

		/// <summary>
		/// Gets user by its login
		/// </summary>
		/// <param name="login"></param>
		/// <returns>User</returns>
		public IUser GetBy(string login)
		{
			if (string.IsNullOrWhiteSpace(login))
			{
				return null;
			}

			var user = Get(u => u.Login.ToLower() == login.ToLower()).FirstOrDefault();
			return user;
		}

		/// <summary>
		/// Insert new user
		/// </summary>
		/// <param name="user"></param>
		/// <returns>User</returns>
		public IUser AddOrUpdate(IUser user)
		{

			if (user == null)
			{
				return null;
			}

			var current = Get(u => u.Login == user.Login).FirstOrDefault();
			if (current != null)
			{
				user.MapUpdate<IUser, User>(current);
				Update(current);
				return current;
			}
			else
			{
				current = new User();
				user.MapUpdate<IUser, User>(current);
				base.Insert(current);
			}
			return current;
		}

		#endregion Methods
	}
}